package tech.yangzhijie.basic.mybatis;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import tech.yangzhijie.basic.mybatis.entity.User;
import tech.yangzhijie.basic.mybatis.mapper.UserMapper;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Hello world!
 *
 */
public class MybatisTests {
    public static void main(String[] args) {
        String resource = "mybatis-config.xml";
        try {
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //初始化配置文件 使用DefaultSqlSessionFactory
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //使用DefaultSqlSessionFactory
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //通过动态代理生成接口代理对象
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            User user = mapper.selectUser(5);
            System.out.println(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private UserMapper mapper;

    @Before
    public void before() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        mapper = sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void 测试mybatis() {
        User user = mapper.selectById(1);
        System.out.println(user);
    }

    @Test
    public void 测试in() {
        List<User> users1 = mapper.select1();
        System.out.println(users1);

        List<User> users2 = mapper.select2("2,1");
        System.out.println(users2);
    }
}
